package ee.nutilovi.praktikaportaal.user;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.Entity;




import ee.nutilovi.praktikaportaal.tools.CryptoTools;
import ee.nutilovi.praktikaportaal.tools.VerificationTools;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String username = req.getParameter("username");
		String password = req.getParameter("password");
		Entity user;
		try {
			user = VerificationTools.isCorrectLogin(username, password);
		} catch (NoSuchAlgorithmException e1) {
			resp.sendRedirect("/error");
			return;
		}
		
		if (user == null) {
			resp.sendRedirect("/usernotfound");
			return;
		}
		
		String userHash = null;
		try {
			userHash = CryptoTools.hashUser(username);
		} catch (NoSuchAlgorithmException e) {
			resp.sendRedirect("/error");
		}		
		
		String idCookieValue = username + "|" + userHash;
		Cookie idCookie = new Cookie("userId", idCookieValue);
		idCookie.setPath("/");
		
		boolean isAdmin = (boolean) user.getProperty("admin");
		String adminCookieValue = null;
		if (isAdmin) {
			String adminHash;
			try {
				adminHash = CryptoTools.hashUser("true");
			} catch (NoSuchAlgorithmException e) {
				resp.sendRedirect("/error");
				return;
			}
			adminCookieValue = "true" + "|" + adminHash;
		} else {
			String adminHash;
			try {
				adminHash = CryptoTools.hashUser("false");
			} catch (NoSuchAlgorithmException e) {
				resp.sendRedirect("/error");
				return;
			}
			adminCookieValue = "false" + "|" + adminHash;
		}
		
		Cookie adminCookie = new Cookie ("isAdmin", adminCookieValue);
		idCookie.setPath("/");
		
		resp.addCookie(idCookie);
		resp.addCookie(adminCookie);
		resp.sendRedirect("/welcome");
	}
}
